//
//  AIInAppPurchaseTool.m
//  Mia
//
//  Created by Vill on 2024/1/16.
//

#import "AIInAppPurchaseTool.h"

@implementation AIInAppPurchaseTool

+ (instancetype)sharedTool{
    static dispatch_once_t once;
    static AIInAppPurchaseTool *instance;
    dispatch_once(&once, ^{
        instance = [[AIInAppPurchaseTool alloc] init];
    });
    return instance;
}

- (instancetype)init {
    if (self = [super init]) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
    return self;
}

- (void)startBuyProducts:(NSSet *)products {
    if ([SKPaymentQueue canMakePayments]) {
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:products];
        request.delegate = self;
        [request start];
    } else {
        if (self.cannotStartBlock) {
            self.cannotStartBlock();
        }
        [SVProgressHUD showInfoWithStatus:@"This device isn't able or allowed to make payments"];
    }
}

#pragma mark - SKPaymentTransactionObserver, SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
   NSArray *product = response.products;
   //如果服务器没有产品
   if ([product count] == 0) {
       dispatch_async(dispatch_get_main_queue(), ^{
           if (self.productNotExist) {
               self.productNotExist();
           }
           [SVProgressHUD showInfoWithStatus:@"The product is not exist"];
       });
       return;
   }
   SKProduct *requestProduct = nil;
   for (SKProduct *pro in product) {
       NSLog(@"%@ -- %@ -- %@ -- %@ -- %@ ", [pro description],[pro localizedTitle],[pro localizedDescription],[pro price],[pro productIdentifier]);
       requestProduct = pro;
   }
   // 12.发送购买请求
   SKPayment *payment = [SKPayment paymentWithProduct:requestProduct];
   [[SKPaymentQueue defaultQueue] addPayment:payment];
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
   NSLog(@"error:%@", error);
   dispatch_async(dispatch_get_main_queue(), ^{
       if (self.requestErrorBlock) {
           self.requestErrorBlock(error);
       }
   });
}

//反馈请求的产品信息结束后
- (void)requestDidFinish:(SKRequest *)request {
    NSLog(@"信息反馈结束");
}

// 13.监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction {
   for (SKPaymentTransaction *tran in transaction) {
       switch (tran.transactionState) {
           case SKPaymentTransactionStatePurchased:
               if (self.buySuccessBlock) {
                   self.buySuccessBlock(tran);
               }
               NSLog(@"done");
               break;
           case SKPaymentTransactionStatePurchasing:
               NSLog(@"Item added to list");
               break;
           case SKPaymentTransactionStateRestored:
               NSLog(@"Goods have been purchased");
               if (self.buyFailBlock) {
                   self.buyFailBlock(@"Please retry", tran);
               }
               [[SKPaymentQueue defaultQueue] finishTransaction:tran];
               break;
           case SKPaymentTransactionStateFailed:
               NSLog(@"fail");
               if (self.buyFailBlock) {
                   self.buyFailBlock(@"Transaction failed", tran);
               }
               [[SKPaymentQueue defaultQueue] finishTransaction:tran];
               break;
           default:
               break;
       }
   }
}

- (void)dealloc {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

@end
